import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useEmployeeStore } from '/@/stores/employee-info';
import pinia from '/@/stores/index';
import { Session } from '/@/utils/storage';
import MESSAGE from '/@/enums/message-enum';

const apiBasePath = (import.meta.env.VITE_API_BASE_PATH as string);

// 配置新建一个 axios 实例
const service = axios.create({
	baseURL: import.meta.env.VITE_API_URL as any,
	timeout: 50000,
	headers: { 'Content-Type': 'application/json' },
});

// 添加请求拦截器
service.interceptors.request.use(
	(config) => {
		const employeeStore = useEmployeeStore(pinia);
		const hasLogin = employeeStore.getHasLogin();
		// 在发送请求之前做些什么 token
		if (hasLogin) {
			let token = employeeStore.getToken();
			(<any>config.headers).common['Authorization'] = `${token}`;
		}
		// 拼装根目录
		const baseUrl = (import.meta.env.VITE_API_BASE_PATH as string);
		config.url = apiBasePath + config.url;
		return config;
	},
	(error) => {
		// 对请求错误做些什么
		return Promise.reject(error);
	}
);

// 添加响应拦截器
service.interceptors.response.use(
	(response) => {
		// 对响应数据做点什么
		const res = response.data;
		if(res.code && res.code === MESSAGE.OK) {
			return response;
		}
		// `token` 过期或者账号已在别处登录
		if (res.code === MESSAGE.NO_LOGIN) {
			Session.clear(); // 清除浏览器全部临时缓存
			window.location.href = '/'; // 去登录页
			ElMessageBox.alert('你已被登出，请重新登录', '提示', {})
				.then(() => {})
				.catch(() => {});
		}
		ElMessage.error(res.msg);
		return response;
	},
	(error) => {
		// 对响应错误做点什么
		if (error.message.indexOf('timeout') != -1) {
			ElMessage.error('网络超时');
		} else if (error.message == 'Network Error') {
			ElMessage.error('网络连接错误');
		} else if (error.message == 'Request failed with status code 404') {
			const {data} = error.response; 
			ElMessage.error('【' + data.path + '】' + '不存在');
		} else {
			ElMessage.error(error.message);
		}
		return Promise.reject(error);
	}
);

// 导出 axios 实例
export default service;
